<?php
//if(!defined('IN_CRONLITE'))exit();

class CACHE implements ArrayAccess {
    private $loadedData = [];
    private $isInitialized = false;

    public function save($value) {
        if (is_array($value)) $value = serialize($value);
        $value = addslashes($value);
        $sql = "UPDATE `".dbconfig['sqlname']."config` SET `v`='$value' WHERE `k`='cache'";
        return executeSQLQuery($sql, 'update');
    }

    public function pre_fetch() {
        global $_CACHE;
        if (!$this->isInitialized) {
            $_CACHE = $this->update();
            $this->loadedData = $_CACHE;
            $this->isInitialized = true;
        }
        return $this;
    }

    public function update() {
        $cache = array();
        $sql = "SELECT * FROM `".dbconfig['sqlname']."config` WHERE 1";
        $query = safeSqlQuery($sql, []);
        if (!empty($query['result'])) {
            foreach ($query['result'] as $result) {
                $cache[$result['k']] = $this->parseValue($result['v']);
            }
        }
        $this->loadedData = $cache;
        return $cache;
    }

    public function clear() {
        $sql = "UPDATE `".dbconfig['sqlname']."config` SET `v`='' WHERE `k`='cache'";
        $this->loadedData = [];
        $this->isInitialized = false;
        return executeSQLQuery($sql, 'update');
    }
    public function updateConfig($data) {
        foreach ($data as $k => $v) {
            saveSetting($k, $v);
        }
        $this->clear(); // 清除缓存
        return true;
    }

    private function getValue($key) {
        if (!$this->isInitialized) {
            $this->pre_fetch();
        }

        if (isset($this->loadedData[$key])) {
            return $this->loadedData[$key];
        }

        return null;
    }

    private function parseValue($value) {
        // 添加调试信息
        $debug = debug;  
        // 判断空值
        if ($value === null || $value === '') {
            return $value;
        }
    
        if (!is_string($value)) {
            if ($debug) error_log("Value is not a string: " . gettype($value));
            return $value;
        }
    
        // 尝试反序列化
        if (preg_match('/^[abOsNdi]:[0-9]+:.*/', $value)) {
            try {
                $unserialize = @unserialize($value);
                if ($unserialize !== false) {
                    return $unserialize;
                }
                if ($debug) error_log("Unserialize failed for value: " . substr($value, 0, 100));
            } catch (Exception $e) {
                if ($debug) error_log("Unserialize exception: " . $e->getMessage());
            }
        }
    
        // 尝试 JSON 解码
        if (in_array($value[0], ['{', '[', '"']) || is_numeric($value)) {
            try {
                $decoded = json_decode($value, true);
                if (json_last_error() === JSON_ERROR_NONE) {
                    return $decoded;
                }
                if ($debug) error_log("JSON decode failed: " . json_last_error_msg());
            } catch (Exception $e) {
                if ($debug) error_log("JSON decode exception: " . $e->getMessage());
            }
        }
    
        // 处理数字
        if (is_numeric($value)) {
            return strpos($value, '.') !== false ? (float)$value : (int)$value;
        }
    
        return $value;
    }

    public function preload($keys = []) {
        if (!$this->isInitialized) {
            $this->pre_fetch();
        }
    }

    public function __get($key) {
        return $this->getValue($key);
    }

    public function offsetExists($offset): bool {
        if (!$this->isInitialized) {
            $this->pre_fetch();
        }
        return isset($this->loadedData[$offset]);
    }

    #[\ReturnTypeWillChange]
    public function offsetGet($offset) {
        return $this->getValue($offset);
    }

    public function offsetSet($offset, $value): void {
        if (!$this->isInitialized) {
            $this->pre_fetch();
        }
        $this->loadedData[$offset] = $value;
    }

    public function offsetUnset($offset): void {
        if (!$this->isInitialized) {
            $this->pre_fetch();
        }
        unset($this->loadedData[$offset]);
    }

    // 获取所有配置
    public function getAll() {
        if (!$this->isInitialized) {
            $this->pre_fetch();
        }
        return $this->loadedData;
    }
}

function saveSetting($k, $v) {
    if ($k === 'pay_work_name') {
        $v = $v; // 支持 HTML
    } elseif (is_array($v)) {
        $v = json_encode($v, JSON_UNESCAPED_UNICODE);
    } else {
        $v = daddslashes($v);
    }

    $sql = "REPLACE INTO `".dbconfig['sqlname']."config` SET `v`=:v, `k`=:k";
    return safeSqlQuery($sql, ['v'=>$v, 'k'=>$k], 'update');
}